package com.roc.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.roc.exception.TaskException;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;

public class FileUtil {
	
	static Logger logger = LogManager.getLogger(FileUtil.class);
	
	private static final int BUFFER_SIZE = 1024;

	public static void uploadFile(File myFile, String myFileFileName,
			Long merchantId) throws TaskException {
		InputStream is = null;
		OutputStream os = null;
		try {
			is = new FileInputStream(myFile);
			// 创建目录，以taskid为目录
			File file = new File(getFilePath(merchantId));
			if (!file.exists()) {
				file.mkdirs();
			}
			// 设置目标文件
			File toFile = new File(file.getPath(), myFileFileName);
			if (toFile.exists()) {
				toFile.delete();
			}
			os = new FileOutputStream(toFile);
			byte[] b = new byte[BUFFER_SIZE];
			int len = is.read(b);
			while (len != -1) {
				os.write(b, 0, len);
				len = is.read(b);
			}
		} catch (Exception e) {
			logger.error(merchantId+"："+myFileFileName+"文件保存失败", e);
			throw new TaskException(e.getMessage());
		} finally {
			try {
				is.close();
				os.close();
			} catch (IOException e) {
				logger.error(merchantId+"："+myFileFileName+"文件流关闭失败", e);
				throw new TaskException(e.getMessage());
			}
		}
	}
	
	public static String getFilePath(Long merchantId) {
		String path = File.separator;
		String rootPath = ConfigProperties.getSystemConfig(Constant.SYSTEM_UPLOAD_FILE_ROOT_PATH_KEY);
		if(StringUtils.isNotBlank(rootPath)){
			path = rootPath;
		}
		return path + merchantId;
	}
}
